package edu.biwu.request;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
import java.util.stream.Collectors;

//处理多文件上传
@WebServlet("/req/upload02")
@MultipartConfig
public class RequestUpload02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.利用request对象中的getParts()方法获取所有的上传文件信息
        //每个上传文件的信息对应一个Part，然后将所有Part存储到一个集合中
        Collection<Part> parts = request.getParts();

        //2.遍历所有的Part（所有的上传文件）
        for (Part uploadFile : parts) {
            String fileName = uploadFile.getSubmittedFileName();

            String extension = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + extension;

            //3.将上传的文件写入到服务端的某个位置，
            File file = new File("D:/uploadFile");
            if (!file.exists()){
                file.mkdir();
            }

            //4.将上传的文件写入到服务端的某个位置上，存储上传文件
            uploadFile.write(file + "/" + newFileName);//直接上传文件写入指定位置
        }

        //5.上传成功后，响应上传成功提示
        String fileNames = parts.stream().map(part -> part.getSubmittedFileName())
                .collect(Collectors.joining(","));

        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(fileNames + "上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
